package com.psa.system;

import android.app.Dialog;
import android.content.DialogInterface;
import android.view.*;
import com.psa.tool.*;
import com.wxw.BaseLibrary.dialog.SToast;
import com.wxw.BaseLibrary.tool.ActivityTool;
import net.duohuo.dhroid.ioc.InjectUtil;
import net.duohuo.dhroid.ioc.annotation.InjectView;
import org.w3c.dom.Attr;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AbsListView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;

import java.util.ArrayList;
/**
 * Created by david on 14-3-24.
 */
public class ConfiguratorActivity extends Activity {
    @InjectView(id = R.id.tvXPath)
    private TextView tvXPath;
    @InjectView(id = R.id.editText1)
    private EditText etValue;
    @InjectView(id = R.id.radioGroup1)
    private RadioGroup rgPage;
    @InjectView(id = R.id.button1)
    private Button btnUp;
    @InjectView(id = R.id.btnCValue)
    private Button btnCValue;
    @InjectView(id = R.id.lvNode)
    private ListView lvNodes;

    @InjectView(id = R.id.etTitle)
    private EditText ft_etTitle;
    @InjectView(id = R.id.etValue)
    private EditText ft_etValue;
    @InjectView(id = R.id.btnOK)
    private Button ft_btnOK;
    @InjectView(id = R.id.btnCancel)
    private Button ft_btnCancel;
    private AlertDialog dialog;

    private Node curNode = null;
    private int ipage = 0;
    private boolean bchanged = false;
    private Node curAttr = null;
    private XmlHelper xmlHelper = null;
    private ArrayList<Node> cList = new ArrayList<Node>();

    /**监听对话框里面的button点击事件*/
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener()
    {
        public void onClick(DialogInterface dialog, int which)
        {
            switch (which)
            {
                case AlertDialog.BUTTON_POSITIVE:// "确认"按钮退出程序
                    setResult(0);
                    finish();
                    break;
                case AlertDialog.BUTTON_NEGATIVE:// "取消"第二个按钮取消对话框
                    break;
                default:
                    break;
            }
        }
    };


    @Override
    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        ActivityTool.hideTitle(this);
        ActivityTool.fullScreen(this);
        setContentView(R.layout.configurator);
        ExitApplication.getInstance().addActivity(this);
        findView();
        xmlHelper = Configurator.getInstance().getXmlHelper();
        curNode = xmlHelper.getXmlDoc().getDocumentElement();
        fullView(curNode);
    }

    private void findView(){
        InjectUtil.inject(this);

/*		etValue.setOnKeyListener(new OnKeyListener(){
			@Override
			public boolean onKey(View v, int keyCode, KeyEvent event) {
				// TODO Auto-generated method stub
				v.setBackgroundColor(Color.YELLOW);
				if(ipage==0)
					curNode.setNodeValue(((EditText)v).getText().toString());
				else {
					curAttr.setNodeValue(((EditText)v).getText().toString());
				}
				return true;
			}
		});*/

        rgPage.setOnCheckedChangeListener(new OnCheckedChangeListener(){

            public void onCheckedChanged(RadioGroup arg0, int arg1) {
                // TODO Auto-generated method stub
                if(arg1==R.id.rChild){
                    ipage = 0;
                } else {
                    ipage = 1;
                }
                fullView(curNode);
            }

        });

        btnUp.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(curNode.getParentNode()!=null)
                    fullView(curNode.getParentNode());
            }

        });

        btnCValue.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(ipage==0){
                    NodeList nodeList = curNode.getChildNodes();
                    Node textNode = null;
                    for (int i=0;i<nodeList.getLength();i++){
                        if (nodeList.item(i).getNodeType()==Node.TEXT_NODE){
                            textNode = nodeList.item(i);
                            textNode.setTextContent(etValue.getText().toString());
                            break;
                        }
                    }
                    if (textNode==null){
                        textNode = xmlHelper.getXmlDoc().createTextNode(etValue.getText().toString());
                        curNode.appendChild(textNode);
                    }
//                    curNode.setTextContent(etValue.getText().toString());
//                    if (!curNode.hasChildNodes() && nodeList.getLength()>0){
//                        for (int i=0;i<nodeList.getLength();i++)
//                            curNode.appendChild(nodeList.item(i));
//                    }
                }
                else {
                    curAttr.setTextContent(etValue.getText().toString());
                }
                fullView(curNode);
                bchanged = true;
            }

        });

        lvNodes.setOnItemClickListener(new OnItemClickListener(){

            public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
                                    long arg3) {
                // TODO Auto-generated method stub
                if(ipage==0)
                    fullView(cList.get(arg2));
                else {
                    curAttr = cList.get(arg2);
                    etValue.setText(curAttr.getNodeValue());
                }
            }

        });
    }

    private void fullView(Node node){
        curNode = node;
        String s = node.getNodeName();
        Node n = node;
        while((n = n.getParentNode())!=null){
            s = n.getNodeName() + "/" + s;
        }
        tvXPath.setText(Configurator.getInstance().getFileName().substring(Configurator.getInstance().getFileName().lastIndexOf("/")+1) + "-" + s);
        cList.clear();
        etValue.setText("");
        if(ipage==0){
            NodeList nl = node.getChildNodes();
            for(int i=0; i<nl.getLength(); i++){
                if(nl.item(i).getNodeType()==Node.ELEMENT_NODE){
                    cList.add(nl.item(i));
                }
                if(nl.item(i).getNodeType()==Node.TEXT_NODE)
                    etValue.setText(nl.item(i).getNodeValue());
            }
        }else{
            NamedNodeMap nnm = node.getAttributes();
            if (nnm != null) {
                for (int i = 0; i < nnm.getLength(); i++) {
                    cList.add(nnm.item(i));
                }
            }
        }
        lvNodes.setAdapter(new MyAdapter(ConfiguratorActivity.this));
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(Menu.NONE, Menu.FIRST + 2, 1, "添加设置项").setIcon(android.R.drawable.ic_menu_add);
        menu.add(Menu.NONE, Menu.FIRST + 1, 2, "保存并关闭").setIcon(android.R.drawable.ic_menu_save);
        return true;
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case Menu.FIRST + 1:
                XmlHelper.write2Xml(xmlHelper.getXmlDoc(), SystemStatus.APP_CONFIG_FILE);
                SToast.showToast(this, "系统设置已经保存!", 1000);
                ConfiguratorActivity.this.setResult(1);
                ConfiguratorActivity.this.finish();
                break;
            case Menu.FIRST + 2:
                showFieldText();
                break;
        }
        return true;
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && bchanged)
        {
            // 创建退出对话框
            AlertDialog isExit = new AlertDialog.Builder(this).create();
            // 设置对话框标题
            isExit.setTitle("系统提示");
            // 设置对话框消息
            isExit.setMessage("配置已经修改，但还未保存。你确定要不保存退出吗？");
            // 添加选择按钮并注册监听
            isExit.setButton(Dialog.BUTTON_POSITIVE, "确定", listener);
            isExit.setButton(Dialog.BUTTON_NEGATIVE, "取消", listener);
            // 显示对话框
            isExit.show();
            return false;
        }else
            return super.onKeyDown(keyCode, event);
    }

    public void showFieldText(){
        LayoutInflater inflater = getLayoutInflater();
        View linearlayout= inflater.inflate(R.layout.fieldtext, null);
        ft_etTitle = (EditText)linearlayout.findViewById(R.id.etTitle);
        ft_etValue = (EditText)linearlayout.findViewById(R.id.etValue);
        ft_btnOK = (Button)linearlayout.findViewById(R.id.btnOK);
        ft_btnCancel = (Button)linearlayout.findViewById(R.id.btnCancel);
        dialog = new AlertDialog.Builder(this).setTitle("请新建项目名称和值").setView(linearlayout).show();
        ft_btnOK.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                if(ft_etTitle.getText().toString().equals("")){
                    SToast.showToast(ConfiguratorActivity.this, "项目名称不能为空", 1000);
                    return;
                }
                dialog.dismiss();
                if(ipage==0){
                    Node node = xmlHelper.createNode(ft_etTitle.getText().toString(), ft_etValue.getText().toString(),
                            xmlHelper.getXmlDoc());
                    curNode.appendChild(node);
                } else {
                    Attr attr = xmlHelper.createAttr(ft_etTitle.getText().toString(), ft_etValue.getText().toString(),
                            xmlHelper.getXmlDoc());
                    curNode.getAttributes().setNamedItem(attr);
                }
                fullView(curNode);
            }

        });
        ft_btnCancel.setOnClickListener(new OnClickListener(){

            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                dialog.dismiss();
            }

        });
    }

    public class MyAdapter extends BaseAdapter {
        private LayoutInflater mInflater;

        public MyAdapter(Context context){
            this.mInflater = LayoutInflater.from(context);
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return cList.size();
        }
        public Object getItem(int arg0) {
            // TODO Auto-generated method stub
            return cList.get(arg0);
        }

        public long getItemId(int arg0) {
            // TODO Auto-generated method stub
            return arg0;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            if(convertView == null){
                Node n = cList.get(position);
                TextView tv = new TextView(mInflater.getContext());
                AbsListView.LayoutParams layoutParams = new AbsListView.LayoutParams(
                        ViewGroup.LayoutParams.MATCH_PARENT, 64);
                tv.setText(n.getNodeName());
                tv.setLayoutParams(layoutParams);
                tv.setGravity(Gravity.LEFT|Gravity.CENTER_VERTICAL);
                tv.setTextSize(20);
                convertView = tv;
            }
            return convertView;
        }
    }
}
